package com.tanhua.mogon.api;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service //不需要暴露服务，只是用来做异步处理，不需要暴露端口，加Service注解几口
public class MovementTimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //申明该方法是异步调用的
    public void saveMovementTimeLine(Movement movement){
        //1.查询当前用户id的好友数据
        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //通过睡眠10秒中的时间，模拟发布动态所需要等待的时间
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //2.循环好友数据，构建好友时间数据表存入数据库
        for (Friend friend : friends) {
            //3.1创建好友时间表对象
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            //3.2封装对象
            //封装某一条动态的id
            movementTimeLine.setMovementId(movement.getId());
            //封装发布改动态的用户Id
            movementTimeLine.setUserId(friend.getUserId());
            //封装该用户好友的id
            movementTimeLine.setFriendId(friend.getFriendId());
            //封装时间线
            movementTimeLine.setCreated(System.currentTimeMillis());
            //3.3调用方法，把数据存储到数据库中
            mongoTemplate.save(movementTimeLine);
        }
    }
}
